import config from './config.js';
import $http from '@/api/request.js'
import stroe from '@/store/index.js'
import API from '@/api/index.js'

// 图片上传
function uploadFile(url, file) {
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: config.baseUrl + url,
			filePath: file,
			name: 'file',
			dataType: "json",
			success: function(uploadFileRes) {
				if (uploadFileRes.data) {
					var type = typeof uploadFileRes.data;
					if (type == 'string') {
						uploadFileRes.data = JSON.parse(uploadFileRes.data)
					}
					resolve(uploadFileRes.data);
				}
			},
			fail: function(res) {
				console.log(res)
			},
			complete: function() {

			}
		})
	})
}

// 图片上传2
function uploadFiles(file) {
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: config.baseUrl + `/zzjApp/uploade?bid=${stroe.state.bid}`,
			filePath: file,
			name: 'file',
			dataType: "json",
			success: function(uploadFileRes) {
				if (uploadFileRes.data) {
					if (typeof uploadFileRes.data != 'object') {
						uploadFileRes.data = JSON.parse(uploadFileRes.data)
					}
					resolve(uploadFileRes.data);
				}

			},
			fail: function(res) {
				console.log(res)
			},
			complete: function() {

			}
		})
	})
}

async function chooseImage(count) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			success: async (res) => {
				const tempFilePaths = res.tempFilePaths;
				let arr = [];
				for (const item of tempFilePaths) {
					let result = await uploadFiles(item);
					let imgItem = result.url.substring(22, result.url.length);
					arr.push(imgItem)
				}
				resolve(arr);
			}
		})
	})
}

// import HTMLParser from "./html-parser.js"
function richTxt(html) {
	var capture = html,
		array = [];
	var i = -1;
	if (html) {
		html = capture.replace(/src=\s*['"]([^'"]+)[^>]*>/gi, function(match, capture) {
				i++;
				if (capture.indexOf('http') > -1) {
					array.push(capture);
					capture = ' src="' + capture +
						'" style="max-width: 100%; height: auto; margin: 0 auto; display: block;" data-index=' + i +
						' />';
					return capture
				} else {
					array.push(config.imgUrl + capture);
					capture = ' src="' + config.imgUrl + capture +
						'" style="max-width: 100%; height: auto; margin: 0 auto; display: block;" data-index=' + i +
						' />';
					return capture
				}
			})
			.replace(/<section/g, '<div').replace(/\/section>/g, '/div>')
			.replace(/<o:p>/g, '').replace(/<\/o:p>/g, '')
			.replace(/<font/g, '<span').replace(/\/font>/g, '/span>')
			.replace(/<table/g, '<table style="max-width:100%;"')
		// html = new HTMLParser(html.trim());
	}
	var obj = {
		html: html,
		imgs: array
	};
	return obj;
}

function call() {
	let phone = uni.getStorageSync('startUp').service_tel;
	if (phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	} else {
		uni.showToast({
			title: "很抱歉，暂未配置联系电话！",
			icon: 'none'
		})
	}
}

function Tel(phone) {
	if (phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	} else {
		uni.showToast({
			title: "很抱歉，暂未配置联系电话！",
			icon: 'none'
		})
	}
}

function toUrl(url) {
	uni.navigateTo({
		url: url
	})
}

function rectTo(url) {
	uni.redirectTo({
		url: url
	})
}

function back(time) {
	uni.navigateBack({
		delta: time ? time : 1
	})
}

function toGoods(goods_id, store_id) {
	if (store_id) {
		uni.navigateTo({
			url: `/pages/goods/goods_detail?goodsid=${goods_id}&shop_id=${store_id}`
		})
	} else {
		uni.navigateTo({
			url: '/pages/goods/goods_detail?goodsid=' + goods_id
		})
	}
}


function istoGoods(type, goods_id, lesson_id) {
	console.log(111);
	if (type == 13) {
		uni.navigateTo({
			url: '/pages/ply/courseDetail?lid=' + lesson_id
		})
	} else {
		uni.navigateTo({
			url: '/pages/goods/goods_detail?goodsid=' + goods_id
		})
	}

}

function backHome() {
	stroe.commit('changeTab', {
		tabId: 1
	});
	uni.redirectTo({
		url: `/pages/index/index`
	})

}


function timeFormat(number, format) {
	/** 
	 * 时间戳转化为年 月 日 时 分 秒 
	 * number: 传入时间戳 
	 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
	 */
	function formatTime(number, format) {
		var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
		var returnArr = [];
		var date = new Date(number * 1000);
		returnArr.push(date.getFullYear());
		returnArr.push(formatNumber(date.getMonth() + 1));
		returnArr.push(formatNumber(date.getDate()));

		returnArr.push(formatNumber(date.getHours()));
		returnArr.push(formatNumber(date.getMinutes()));
		returnArr.push(formatNumber(date.getSeconds()));

		for (var i in returnArr) {
			format = format.replace(formateArr[i], returnArr[i]);
		}
		return format;
	}

	//数据转化  
	function formatNumber(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}
	return formatTime(number, format);
}

// 图片预览
function previewImage(i, imgArry) {
	if (imgArry) {
		let arr = [];
		for (let i in imgArry) {
			arr.push(config.imgUrl + imgArry[i].img)
		}
		uni.previewImage({
			current: i,
			urls: arr,
			indicator: "number",
			loop: true
		})
	}
}

function previewImgs(i, imgArry) {
	if (imgArry) {
		let arr = [];
		const reg = /^(http|https)/;
		for (let i in imgArry) {
			imgArry[i].search(reg) != -1 ? arr.push(imgArry[i]) : arr.push(config.imgUrl + imgArry[i])
		}
		uni.previewImage({
			current: i,
			urls: arr,
			indicator: "number",
			loop: true
		})
	}
}

function previewSingle(imgSingle) {
	if (!imgSingle) return;
	const arrImg = [];
	imgSingle.includes('http') ? arrImg.push(imgSingle) : arrImg.push(config.imgUrl + imgSingle)
	uni.previewImage({
		current: 0,
		urls: arrImg,
		indicator: "number",
		loop: true
	})

}

// H5禁止分享等动作
function H5HideShare() {
	function onBridgeReady() {
		WeixinJSBridge.call('hideOptionMenu');
		WeixinJSBridge.call('hideToolbar');
	}
	if (typeof WeixinJSBridge == "undefined") {
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
}

function strlen(str) {
	var len = 0;
	for (var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		//单字节加1
		if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
			len++;
		} else {
			len += 2;
		}
	}
	return len;
}

function BarTitle(title) {
	uni.setNavigationBarTitle({
		title
	})
}

function ImageNum(i, imgArry) {
	if (imgArry) {
		let arr = [];
		for (let i in imgArry) {
			arr.push(config.imgUrl + imgArry[i])
		}
		uni.previewImage({
			current: i,
			urls: arr,
			indicator: "number",
			loop: true
		})
	}
}

// 分享到朋友圈、复制短链不经过首页强制调接口
function restart(options) {
	console.log('restart', options)

	if ([1154, 1155, 1179].includes(options.scene)) {
		const info = uni.getAccountInfoSync()
		let appid = info.miniProgram.appId
		$http.post({
			url: '/zzj_singleSaleApi/startUp',
			data: {
				appid
			}
		}).then(res => {
			if (res.errcode != 100) return
			let result = res.data
			let obj = {
				bid: res.bid,
				tabBar: res.diy_table_bar.compCont,
				logo: result.logo_img,
				share: result.share,
				nameDefinition: result.nameDefinition,
				startUp: result,
				color: res.themeConfig.colorVal1,
				regInfo: result.regInfo,
				share_v_id: options.query.share_v_id || ''
			}
			stroe.commit('getUser', obj)

			uni.setStorageSync('bid', res.bid)
			uni.setStorageSync('shareData', result.share)
			uni.setStorageSync('startUp', result)
			getApp().globalData.color = res.themeConfig.colorVal1
			if (obj.share_v_id) uni.setStorageSync('share_v_id', obj.share_v_id)
		})
		API.user.getOpenid()
	}
}

function addShareNum(type, id, share_to) {
	$http.post({
		url: '/publicPlugins/addPageShareNum',
		data: {
			type,
			id,
			share_to // 好友/群1、朋友圈2
		}
	}).then(res => {
		if (res.code != 100) return
	})
}

function hexToRgba(hex, opacity) {
  return (
    "rgba(" +
    parseInt("0x" + hex.slice(1, 3)) +
    "," +
    parseInt("0x" + hex.slice(3, 5)) +
    "," +
    parseInt("0x" + hex.slice(5, 7)) +
    "," +
    opacity +
    ")"
  )
}

export default {
	richTxt,
	uploadFile,
	uploadFiles,
	chooseImage,
	call,
	Tel,
	backHome,
	toUrl,
	rectTo,
	previewImage,
	previewImgs,
	timeFormat,
	H5HideShare,
	toGoods,
	istoGoods,
	back,
	strlen,
	BarTitle,
	ImageNum,
	previewSingle,
	restart,
	addShareNum,
	hexToRgba
}